/*
 * Copyright (c) 2020, 2025, keyila All rights reserved.
 *
 */
package com.clp.util;

import com.alibaba.fastjson.JSON;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * @author clp
 * @version 1.0
 */
@Component
public class CacheUtil<K,V> {

    @Value("${guava.cache.switch}")
    public Boolean switchCache;

    //初始化本地缓存
    private Cache<String,String> localCache= CacheBuilder.newBuilder()
            .maximumSize(5000)
            .expireAfterWrite(3, TimeUnit.SECONDS)
            .build();

    public Map<K,V> getResult(List<K> skuIdList, String cachePrefix,
                              Class<V> clazz, Function<List<K>,Map<K,V>> function ){
        //参数校验
        if (CollectionUtils.isEmpty(skuIdList)){
            return Collections.emptyMap();
        }
        //声明结果
        Map<K,V> resultMap=new HashMap<>(16);
        //判断开关
        if (!switchCache){
            resultMap=function.apply(skuIdList);
            return resultMap;
        }
        //声明本地缓存没有的List
        List<K> noCacheList=new ArrayList<>();
        for (K id:skuIdList){
            String cacheKey=cachePrefix + "_" + id;
            String content = localCache.getIfPresent(cacheKey);
            if (StringUtils.isNotBlank(content)){
                //本地缓存当中存在
                V v = JSON.parseObject(content,clazz);
                resultMap.put(id,v);
            }else {
                noCacheList.add(id);
            }
        }
        if (CollectionUtils.isEmpty(noCacheList)){
            return resultMap;
        }
        Map<K,V> noCacheResultMap=function.apply(noCacheList);
        if (noCacheResultMap==null||noCacheResultMap.isEmpty()){
            return resultMap;
        }
        for (Map.Entry<K,V> entry:noCacheResultMap.entrySet()){
            K id = entry.getKey();
            V result = entry.getValue();
            resultMap.put(id,result);
            String cacheKey=cachePrefix + "_" + id;
            localCache.put(cacheKey,JSON.toJSONString(result));
        }
        return resultMap;
    }


}
